package com.homson.servicedomain.domain.account;

import com.homson.coreservice.servicecommon.co.AccountIncomeCO;
import com.homson.coreservice.servicecommon.enumeration.AccountTypeEnum;
import com.homson.coreservice.servicecommon.expection.BizException;
import com.homson.coreservice.serviceinfrastructure.datasource.model.account.AccountDO;
import com.homson.coreservice.serviceinfrastructure.datasource.repository.account.AccountRepository;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * @author: homson_leo
 * @contact: hey_超级巨星（Homson_Leo）- 刘泓岑 1196816884@qq.com
 * @time: 2025/11/1 4:58 PM
 **/
@Service
@Slf4j
public class AccountIncomeCommand {
    
    @Resource
    private AccountQueryCommand accountQueryCommand;
    @Resource
    private AccountRepository accountRepository;
    
    public void addAccountBalance(Long accountId, AccountIncomeCO accountIncomeCO) {
        try{
            AccountTypeEnum accountType = AccountTypeEnum.of(accountIncomeCO.getAccountType());
            if(Objects.isNull(accountType)){
                throw new BizException("不支持的账户类型");
            }
            Boolean accountExist = accountQueryCommand.isAccountExist(accountId, accountType);
            if(!accountExist){
                throw new BizException("账户不存在");
            }
            AccountDO accountDO = accountRepository.findByAccountId(accountId);
            BigDecimal currentBalance = accountDO.getBalance();
            BigDecimal newBalance = currentBalance.add(accountIncomeCO.getAmount());
    
            // 使用CAS进行更新
            accountRepository.updateAccountBalance(accountId, newBalance, accountDO.getVersionId());
        }catch (BizException bizException){
            log.error(AccountIncomeCommand.class.getSimpleName(), bizException.getMessage());
        }
        
    }
    
}
